package com.szgd.controller.project;

import com.szgd.controller.BaseController;
import com.szgd.service.equipment.EquipmentService;
import com.szgd.service.personnel.AttachService;
import com.szgd.service.project.BidService;
import com.szgd.service.project.ProjectService;
import com.szgd.service.project.SiteService;
import com.szgd.util.Constant;
import com.szgd.util.ExcelUtil;
import com.szgd.util.PropertiesUtil;
import com.szgd.util.TimeUtil;
import org.apache.commons.collections.map.HashedMap;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/project")
public class ProjectController extends BaseController {
    private static Logger logger = Logger.getLogger(ProjectController.class);

    @Autowired
    ProjectService projectService;
    @Autowired
    AttachService attachService;

    @RequestMapping(value = "toProjectInfoList", method = RequestMethod.GET)
    public ModelAndView toProjectInfoList(HttpServletRequest request, HttpSession session) {
        ModelAndView mv = this.getModelAndView(request,session,"project/projectInfo/projectInfoList");
        return mv;
    }

    @RequestMapping(value = "toProjectInfoView", method = RequestMethod.GET)
    public ModelAndView toProjectInfoView(HttpServletRequest request, HttpSession session)
    {
        ModelAndView mv = getModelAndView(request,session,"/project/projectInfo/projectInfoView");
        String id = mv.getModelMap().get("id")== null?"":mv.getModelMap().get("id").toString().replace("null","");
        if (id.length() > 0)//修改
        {
            Map<String, Object> projectInfoMap = projectService.getProject(id);
            mv.addObject("project",projectInfoMap);
        }
        return mv;
    }

    @RequestMapping(value = "toProjectInfoForm", method = RequestMethod.GET)
    public ModelAndView toProjectInfoForm(HttpServletRequest request, HttpSession session)
    {
        ModelAndView mv = getModelAndView(request,session,"/project/projectInfo/projectInfoForm");
        String id = mv.getModelMap().get("id")== null?"":mv.getModelMap().get("id").toString().replace("null","");;
        if (id.length() > 0)//修改
        {
            Map<String, Object> projectInfoMap = projectService.getProject(id);
            mv.addObject("project",projectInfoMap);
        }
        return mv;
    }

    @RequestMapping(value = "/getProjectList", method = RequestMethod.GET)
    public void  getProjectList(HttpServletResponse response, HttpServletRequest request){
        Map<String, Object> paramMap = getMapParams(request);
        List<Map<String, Object>> dataList = projectService.getProjectList(paramMap);
        outTableJSONDataCommon(response, dataList);
    }

    @RequestMapping(value = "/getProjectById")
    @ResponseBody
    public  Map<String, Object>  getProjectById(@RequestBody HashMap<String, Object> paramMap,HttpServletResponse response,HttpServletRequest request){
        String id = paramMap.get("id")== null?"":paramMap.get("id").toString().replace("null","");
        Map<String, Object> dataMap = new HashMap<>();
        if (id.length() > 0)
            dataMap = projectService.getProject(id);
        return getSuccMap(dataMap);
    }

    @RequestMapping(value = "/saveProjectInfo")
    @ResponseBody
    public Map<String,Object> saveProjectInfo(@RequestBody HashMap<String, Object> paramMap,HttpServletRequest request,HttpServletResponse response) {
        String id = paramMap.get("id")== null?"":paramMap.get("id").toString().replace("null","");
        HashMap<String, Object> projectAttachMap = (HashMap<String, Object>)paramMap.get("projectAttach");
        String message = "";
        try {
            if (id.length() == 0)//新增
            {
                paramMap.put("creator",this.getLoginId(request.getSession()));
                projectService.insertProject(paramMap);
                id = paramMap.get("id").toString();
            } else {
                paramMap.put("uploader",this.getLoginId(request.getSession()));
                projectService.updateProject(paramMap);
            }
            try{
                String isProjectAttachChanged = projectAttachMap.get("isProjectAttachChanged").toString();
                if (isProjectAttachChanged.equalsIgnoreCase("1"))
                {
                    String parentId = projectAttachMap.get("parentId")== null?"":projectAttachMap.get("parentId").toString().replace("null","");
                    if (parentId.length() == 0)
                        projectAttachMap.put("parentId",paramMap.get("id"));
                    projectAttachMap.put("creator",this.getLoginId(request.getSession()));
                    projectAttachMap.put("uploader",this.getLoginId(request.getSession()));
                    attachService.saveAttach(projectAttachMap);
                }
            }catch(Exception e){
                e.printStackTrace();
                message = message + ",附件保存失败，请重新编辑此信息再保存";
                logger.error("附件保存失败，请重新编辑此信息再保存:项目ID："+id+"---"+e.getMessage());
            }
            if (message.length() > 0 )
                message = "项目信息保存成功！" + " 但" + message;
            else
                message = "项目信息保存成功！";
            return getSuccMap(message);
        }catch(Exception e){
            e.printStackTrace();
            logger.error("项目信息保存失败："+e.getMessage());
            return getSuccMap("项目信息保存失败："+e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping(value = "/batchUploadProjectInfo", method = {RequestMethod.GET, RequestMethod.POST})
    public void batchUploadProjectInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        long startTime = System.currentTimeMillis();
        InputStream in = null;
        List<List<Object>> listob = null;
        MultipartFile file = multipartRequest.getFile("file");
        if (file.isEmpty()) {
            throw new Exception("文件不存在！");
        }
        in = file.getInputStream();
        PrintWriter out = null;
        response.setCharacterEncoding("UTF-8");  //防止ajax接受到的中文信息乱码
        response.setHeader("Content-type", "text/html;charset=UTF-8");   //跟上面同时使用可解决乱码问题
        out = response.getWriter();
        try {
            Map<String, String> fieldMapping = projectService.getFieldMap();
            List<Map<String, Object>> dataList = ExcelUtil.getListByExcel(in, file.getOriginalFilename(), fieldMapping, false);
            String batchNo = TimeUtil.formatDate(Calendar.getInstance().getTime(), "yyyyMMddhhmmss");
            Map<String, Object> resultMap = projectService.batchImportProjectInfo(dataList, this.getLoginId(request.getSession()), batchNo);

            long endTime = System.currentTimeMillis();
            List<Map<String, Object>> successList = (List<Map<String, Object>>) resultMap.get(Constant.IMPORT_HE_SUCCESS);
            List<Map<String, Object>> ignoreList = (List<Map<String, Object>>) resultMap.get(Constant.IMPORT_HE_IGNORE);
            List<Map<String, Object>> failedList = (List<Map<String, Object>>) resultMap.get(Constant.IMPORT_HE_FAILED);
            List<Map<String, Object>> updatedList = (List<Map<String, Object>>) resultMap.get(Constant.IMPORT_HE_UPDATED);
            String errorHtml = failedList.size() + "条";

            if (failedList.size() > 0) {
                //生成失败记录文件
                String fileName = "项目列表" + batchNo + ".xls";
                String filePath = PropertiesUtil.get("batchImportErrorPath");
                String realPath = request.getServletContext().getRealPath(filePath);
                filePath = filePath.replace("\\", "/");
                File f = new File(realPath);
                if (!f.exists()) {
                    f.mkdirs();
                }
                realPath = realPath + File.separator + fileName;
                exportExcelByTemplate(fieldMapping,failedList, realPath,"项目信息批量导入模版.xls");
                String downloadPath = filePath + "/" + URLEncoder.encode(fileName,"UTF-8");
                errorHtml = "<a href='#WEBROOT#/downloadErrorRecord?path=" + downloadPath + "'>" + failedList.size() + "条</a>";
            }
            out.print("本次导入共处理" + dataList.size() + "条数据[新增：" + successList.size() + "条，更新："
                    + updatedList.size() + "条，<font color='red'>失败：" + errorHtml
                    + "</font>]，耗时： "
                    + (endTime - startTime) / 1000 + "秒！");
        } catch (Exception e) {
            out.print("文件导入失败！");
            logger.error(e.getMessage());
        }
        out.flush();
        out.close();
    }

    @RequestMapping(value = "/deleteProject")
    @ResponseBody
    public Map<String,Object> deleteProject(@RequestBody HashMap<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
        try{
            paramMap.put("uploader",this.getLoginId(request.getSession()));
            projectService.deleteProject(paramMap);

            String message = "项目信息删除成功！";
            return getSuccMap(message);
        }catch (Exception e)
        {
            e.printStackTrace();
            logger.error("项目信息删除失败："+e.getMessage());
            return getSuccMap("项目信息删除失败："+e.getMessage());
        }
    }

    @RequestMapping(value = "/saveAttach")
    @ResponseBody
    public Map<String,Object> saveAttach(@RequestBody HashMap<String, Object> paramMap,HttpServletRequest request,HttpServletResponse response) {
        try {
            String isProjectAttachChanged = paramMap.get("isProjectAttachChanged").toString();
            if (isProjectAttachChanged.equalsIgnoreCase("1"))
            {
                String parentId = paramMap.get("parentId")== null?"":paramMap.get("parentId").toString().replace("null","");
                if (parentId.length() == 0)
                    paramMap.put("parentId",paramMap.get("id"));
                attachService.saveAttach(paramMap);
            }
            return getSuccMap("附件上传成功");
        }catch(Exception e){
            e.printStackTrace();
            logger.error("附件上传失败："+e.getMessage());
            return getSuccMap("附件上传失败："+e.getMessage());
        }
    }
}
